/*
 * Copyright 2007,2008 Anton Dignoes, Daniel Rampanelli, Martin Palma
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.googlecode.webduff.store;

import java.io.File;


import org.tmatesoft.svn.core.SVNException;
import org.tmatesoft.svn.core.SVNURL;
import org.tmatesoft.svn.core.internal.io.fs.FSRepositoryFactory;
import org.tmatesoft.svn.core.io.SVNRepository;
import org.tmatesoft.svn.core.io.SVNRepositoryFactory;

import com.googlecode.webduff.WebDuffConfiguration;
import com.googlecode.webduff.authentication.provider.Credential;
import com.googlecode.webduff.exceptions.WebdavException;
import com.googlecode.webduff.io.URI;

/**
 * Abstract class representing a Factory for WebdavStores implementing the configuration part
 * 
 * @author Anton Dignoes, Daniel Rampanelli, Martin Palma
 *
 */
public abstract class WebDuffStoreFactory implements WebdavStoreFactory {
	
	private static org.apache.log4j.Logger log = org.apache.log4j.Logger.getLogger(WebDuffStoreFactory.class);
	
	protected static WebDuffSVNRepository theRepository = null;
	
	/**
	 * Method to initialize the SVNRepository which data is specified in <code>config</code>
	 */
	public void init(WebDuffConfiguration config) {
		URI storeURI = config.getPath("src");
		FSRepositoryFactory.setup();
		
		// make SVN Repository & WebDuff SVN repository as singleton
		if(theRepository == null) {
			try {
				SVNRepository aSVNRepository = SVNRepositoryFactory.create(SVNURL.parseURIEncoded("file://" + storeURI.getPath()));
				try {
					aSVNRepository.testConnection();
				} catch (SVNException e) {
					// that means, this is not a valid repository
					aSVNRepository = SVNRepositoryFactory.create(SVNRepositoryFactory.createLocalRepository(new File(storeURI.getPath(System.getProperty("file.separator"))), true, true));
					log.info("Creating new repository at location \"" + storeURI.getPath() + "\"");
				}
				theRepository = new WebDuffSVNRepository(aSVNRepository);
			} catch(SVNException e) {
				log.debug("Exception (create)");
				log.debug(e.getMessage());
				throw new WebdavException(e.getMessage());
			}
		}
	}

	public abstract WebdavStore create(Credential credential);

}